package com.xueyi.aixihu.config;

import com.alibaba.fastjson.JSON;
import com.xueyi.aixihu.entity.vo.AccessTokenDefinition;
import com.xueyi.aixihu.entity.vo.Oauth2WxLoginRequest;
import com.xueyi.aixihu.mapper.BindWxMapper;
import com.xueyi.aixihu.utils.WeChatDevUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 描述 微信的Config
 *
 * @auther 俞烨
 * @date 2022-08-16 11
 */
@Controller
@Slf4j
public class WeChatConfig {

    @Autowired
    HttpServletRequest request;

    public static final String WX_GZH_APP_ID = "wx025fe1541980faae";
    public static final String WX_GZH_SECRET = "09a4a7437306aa0f6acf2b174067af78";
    /**
     * 微信公众号的openId
     */
    /* public static final String WX_GZH_APP_ID = "wx58e6bbc5cda8c37d";
     */
    /**
     * 微信公众号的密钥
     *//*
    public static final String WX_GZH_SECRET = "d72ae959dfcf284c747b0d9b5859b276";*/


    @Autowired
    BindWxMapper bindWxMapper;

    /**
     * 微信回调
     *
     * @param oauth2WxLoginRequest
     * @return
     */
    @RequestMapping("/bind/wx")
    public String axhBindWx(Oauth2WxLoginRequest oauth2WxLoginRequest) {

        log.info("微信绑定: {} ", JSON.toJSONString(oauth2WxLoginRequest));
        String state = oauth2WxLoginRequest.getState();
        if (StringUtils.isEmpty(oauth2WxLoginRequest.getCode()) || StringUtils.isEmpty(state)) {

            request.setAttribute("error_msg", "微信服务端携带数据校验异常，请联系管理员。");
            return "XcxAuthError";
        }

        // 获取用户的openId
        AccessTokenDefinition weChatGzhOpenId = WeChatDevUtil.getWeChatGzhOpenId(oauth2WxLoginRequest.getCode(), WeChatConfig.WX_GZH_APP_ID, WeChatConfig.WX_GZH_SECRET);

        if (weChatGzhOpenId == null) {

            request.setAttribute("error_msg", "获取用户的OpenId失败，请重新打开小程序进行授权");
            return "XcxAuthError";
        }

        // 通过返回过来的state进行切割用户的token和角色信息
        bindWxMapper.updateUserWxOpenId(weChatGzhOpenId.getOpenid(), Integer.parseInt(state));
        log.info("绑定微信成功");
        return "XcxAuth";
    }
}
